<?php 
  require_once("includes/config.php"); 
  if(isset($_POST['date']))
  {
      $result = query("INSERT INTO payment_vouchers (contract_id, amen_sondoq, recipient, amount,paymen_method,reason
	                 ,notes,miladi_date,Hijri_date,owner_id) VALUES (?,?,?,?,?,?,?,?,?,?)", 
      $_POST['contract_id'],$_POST['amen_sondoq'],$_POST['recipient'],$_POST['amount'],$_POST['type'],$_POST['reason'],$_POST['notes'],$_POST['date'],$_POST['hijri-date'],$_SESSION['user_id']);
    $id = query("getlastid");
    $updatePaid = query("UPDATE contracts SET paid_back = paid_back + ? where contract_id = ? ",$_POST['amount'], $_POST['contract_id']);
    echo $id;
  }
  else
  {
    $length = 20;
    
    if( isset($_POST['page'])  && !empty($_POST['page'] ))
    {
      $page =  filter_var($_POST['page'], FILTER_SANITIZE_NUMBER_INT);
      $start = $page*20 - 20;
    }
    else
    {
      $start = 0;
      $page = 1;
    }
    
    $sql = "SELECT payment_vouchers.*,contracts.contract_id As contract__id,contracts.contract_status FROM payment_vouchers LEFT JOIN contracts ON payment_vouchers.contract_id = contracts.contract_id WHERE payment_vouchers.owner_id= ?";
    $sqlCount = "SELECT COUNT(*) FROM payment_vouchers WHERE owner_id = ?";
    
    $binds['owner_id'] = $_SESSION['user_id'];
  
    if(!empty($_POST['from']) && !empty($_POST['to']))
    {
      $binds['from'] = $_POST['from'];
      $binds['to'] = $_POST['to'];
      $sql .= " and miladi_date between ? AND ?";
      $sqlCount .= " and miladi_date between ? AND ?";
    }
                  
    if(!empty($_POST['contract_id']) )
    {
      $binds['contract_id'] = $_POST['contract_id'];
      $sql .= " and payment_vouchers.contract_id = ?";
      $sqlCount .= " and payment_vouchers.contract_id = ?";
    }
          
    if(!empty($_POST['payment_id']))
    {
      $binds['payment_id'] = $_POST['payment_id'];
      $sql .= " and payment_vouchers.payment_id = ?";
      $sqlCount .= " and payment_vouchers.payment_id = ?";
    }
          
    $sql .= " LIMIT ?,?";
    $binds['start'] = $start;
    $binds['end'] = $length;
    
    //dump($sql);
    $payments = query($sql,$binds);
    $sqlCount = query($sqlCount,$binds);
    
    $totalPages = $sqlCount[0]['COUNT(*)'];
   
    render("payment_vouchers.php", array("title"=>"ادارة سندات الصرف","page"=>$page,"totalPages"=>$totalPages,"payments"=>$payments,"start"=>$start,"length"=>$length,"binds"=>$binds));
  }
?>